package com.data;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DbConnectionManager {
	
	private final int MAX_CONNECTIONS = 10;
	
	private String driverName = "org.postgresql.Driver";
	private String url = "jdbc:postgresql://localhost:5432/dev";
	private String username = "test";
	private String password = "test";
	private Connection [] connections;
	private boolean [] canUse;
	private int availableConn = MAX_CONNECTIONS;
	
	public DbConnectionManager(){
		connections = new Connection[MAX_CONNECTIONS];
		canUse = new boolean[MAX_CONNECTIONS];
		connect();
	}

	public void connect(){
		synchronized(connections){
			try {
				Class.forName(driverName);
			} catch (ClassNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			for(int i = 0;i<MAX_CONNECTIONS;i++){
				try {
					connections[i] = DriverManager.getConnection(url,username,password);
					canUse[i] = true;
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					canUse[i] = false; //
					availableConn--;
					e.printStackTrace();

				}  
			}
		}
	}

	public void closeAll(){
		synchronized(connections){
			for(int i = 0;i<MAX_CONNECTIONS;i++){
				try {
					connections[i].close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				canUse[i] = false;
				availableConn--;
			}
		}
	}
	
	public Connection getConnection(){
		synchronized(connections){
			//Ghetto, fix later, dirty busy loop
			while(true){
				if(availableConn<=0){
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				else{
					break;
				}
			}
			for(int i = 0;i<MAX_CONNECTIONS;i++){
				if(canUse[i]){
					canUse[i] = false;
					return connections[i];
				}
			}
			//Should never return null
			return null;
		}
	}
	
	public void returnConnection(Connection c){
		for(int i = 0;i<MAX_CONNECTIONS;i++){
			if(c==connections[i]){
				canUse[i] = true;
				availableConn++;
				break;
			}
		}
	}
	
}
